package org.ash.user.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.ash.base.constant.MessageConstant;
import org.ash.base.model.Result;
import org.ash.base.ustils.RegexUtil;
import org.ash.user.pojo.dto.*;
import org.ash.user.pojo.User;
import org.ash.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

import static org.ash.base.constant.MessageConstant.*;

/**
 * 管理员后端对用户的操作
 */
@RestController
@RequestMapping("/user")
@Slf4j
@Api(tags = "用户接口类")
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation(value = "根据ID查找用户")
    @GetMapping("/list/{id}")
    public Result findById(@PathVariable("id") Long id) {
        User user = userService.getById(id);
        if (user == null) {
            return Result.error(ACCOUNT_NOT_FOUND);
        }
        log.info("user 的具体消息为{}", user);
        return Result.success(user);
    }

    @ApiOperation(value = "条件查询用户")
    @PostMapping("/query")
    public Result queryUsers(@RequestBody UserQueryDTO userQueryDTO) {
        List<User> users = userService.queryUsers(userQueryDTO);
        return Result.success(users);
    }

    @ApiOperation(value = "分页查询用户")
    @GetMapping("/page")
    public Result getUserByPage(@RequestParam int current, @RequestParam int size) {
        log.info("进行分页查询");
        Page<User> page = new Page<>(current, size);
        return Result.success(userService.page(page));
    }

    @ApiOperation(value = "根据ID删除用户")
    @DeleteMapping("/delete/{id}")
    public Result deleteById(@PathVariable("id") Long id) {
        log.info("删除id为{}的用户", id);
        boolean remove = userService.removeById(id);
        if (!remove) {
            return Result.error("删除用户失败");
        }
        return Result.success();
    }

    @ApiOperation(value = "新增用户")
    @PostMapping("/add")
    public Result addUser(@RequestBody @Valid UserUpdateDTO userUpdateDTO) {
        User user = userService.addUser(userUpdateDTO);
        return Result.success(user);
    }

    @ApiOperation(value = "编辑用户信息")
    @PutMapping("/update/{id}")
    public Result updateById(@PathVariable("id") Long id, @RequestBody @Valid UserUpdateDTO userUpdateDTO) {
        User user = userService.updateById(id, userUpdateDTO);
        return Result.success(user);
    }

    @ApiOperation(value = "用户名登录")
    @PostMapping("/login/username")
    public Result loginWithUsername(@RequestBody @Valid LoginFormDTO loginFormDTO) {
        log.info("用户名登录：{}", loginFormDTO);
        User loggedInUser = userService.loginWithUsername(loginFormDTO);;

        // 处理返回结果
        if (loggedInUser == null) {
            return Result.error(MessageConstant.LOGIN_FAILED);
        }
        return Result.success(loggedInUser);
    }

    @ApiOperation(value = "手机号登录")
    @PostMapping("/login/phone")
    public Result loginWithPhone(@RequestBody @Valid LoginPhoneFormDTO loginFormDTO) {
        log.info("手机号登录：{}", loginFormDTO);
        User loggedInUser = userService.loginWithPhone(loginFormDTO);;

        // 处理返回结果
        if (loggedInUser == null) {
            return Result.error(MessageConstant.LOGIN_FAILED);
        }
        return Result.success(loggedInUser);
    }

    @ApiOperation(value = "用户注册")
    @PostMapping("/register")
    public Result register(@RequestBody @Valid RegisterFormDTO registerFormDTO) {
        log.info("用户注册请求: {}", registerFormDTO);

        User register = userService.register(registerFormDTO);
        if(register == null){
            return Result.error("注册失败");
        }
        return Result.success(register);
    }

    @ApiOperation(value = "发送验证码")
    @PostMapping("/code")
    public Result sendCode(@RequestParam("phone") String phone) {
        // 发送短信验证码并保存验证码
        String code = userService.sendCode(phone);
        if (RegexUtil.isCodeInvalid(code)) {
            // 生成验证码失败
            return Result.error(MessageConstant.CODE_GENERATE_FAILED);
        }
        return Result.success(code);
    }


}
